<template>
    <el-dialog :title="title" v-model="visible" width="480px" :close-on-click-modal="false" @close="emits('close')">
        <el-form ref="formRef"
                 :model="form"
                 :rules="formRules"
                 :label-width="140">
          
            <el-form-item label="姓名:" prop="real_name">
                <el-input v-model="form.real_name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            
            <el-form-item label="手机号:" prop="mobile" >
                <el-input v-model="form.mobile" placeholder="输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="登录密码:" prop="passwd">
                <el-input v-model="form.passwd" placeholder="请输入登录密码"></el-input>
            </el-form-item>
            <el-form-item label="部门:" prop="department_id">
                <!-- <el-select v-model="form.department_id" placeholder="请选择部门">
                    <el-option v-for="(item,index) in departList" :key="index" :label="item.department_name" :value="item.id"></el-option>
                    
                </el-select> -->
                <el-tree-select v-model="form.department_id" 
                                style="width:100%"
                                check-strictly
                                :data="departList" 
                                :render-after-expand="false"
                                :props="{
                                    label:'department_name',
                                    value:'id',
                                    children:'children'
                                }"></el-tree-select>
            </el-form-item>
           
           
            <el-form-item label="角色权限" prop="role_id">
                <el-select v-model="form.role_id" placeholder="请选择角色权限">
                    <el-option v-for="(item,index) in roleList" :key="index" :label="item.role_name" :value="item.id"></el-option>
                
                </el-select>
                
            </el-form-item>
            <el-form-item label="查看数据范围:" prop="data_permission_type">
                <el-radio-group v-model="form.data_permission_type">
                    <el-radio label="1">本人</el-radio>
                    <el-radio label="2">本部</el-radio>
                    <el-radio label="3">全部</el-radio>

                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注:" prop="remark">
                <el-input v-model="form.remark" type="textarea"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="emits('close')">取 消</el-button>
                <el-button type="primary" @click="save(formRef)">确 定</el-button>
            </div>
        </template>
        
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed, nextTick, onMounted} from 'vue'
import { ElMessage } from 'element-plus'

import type { FormInstance, FormRules, CascaderProps } from 'element-plus'

import { getUserDetail, saveUser, editUser } from 'services/setting'

import { getRegion,getDepartList,getRoleList } from 'services/system'

import systemStore from '@/store/modules/system'

const $systemStore = systemStore()

const emits = defineEmits(['close', 'success'])

const formRef = ref<FormInstance>()

const form = ref({
    id: undefined,
    mobile: '',
    real_name: '',
    passwd: '',
    role_id: '',
    department_id: '',
    data_permission_type:'1',
    remark:''
})

const checkPhone = (rule:any,value:any,callback:any) => {
    let reg = /^1[0-9]{10}$/;
    
    if (value === '') {
        callback(new Error('请输入手机号'))
    } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
    } else {
        callback()
    }
}

const formRules = reactive<FormRules>({
    account:[{required:true,message:'请输入账号名'},{max:10,message:'最多只能10个文字'}],
    name:[{required:true, message:'请输入姓名'}],
    mobile:[{required:true, validator:checkPhone, trigger:'blur'}],
})

const props = defineProps<{
    dialogVisible:boolean,
    id?:number,
    state:string,
    departTree?:[]
}>();

const visible = ref(false)


watch(() => props.dialogVisible, async (val) => {
    visible.value = val
    console.log(props.state)
    if (visible.value === true) {
        await nextTick()
        if (props.state == 'edit') {
            if (props.id) {
                getDetail(props.id)
            }
        } else {
            formRef.value?.resetFields()
            form.value.id = undefined

        }
        
    }
},{
    immediate:true
})

const title = computed(() => {
    return props.state == 'add' ? '新增账号' : '编辑账号'
})

const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            let data = JSON.parse(JSON.stringify(form.value))
            
            if (data.id) {
                editUser(data).then(res => {
                    ElMessage.success('操作成功')
                    emits('success')
                })
            } else {
                saveUser(data).then(res => {
                    ElMessage.success('操作成功')
                    emits('success')
                })
            }
           
        } else {
            console.log('error submit', fields)
        }
    }) 
}

const getDetail = (id:number) => {
    getUserDetail({id}).then((res:any) => {        
        form.value = res
    })
}
const departList = ref<any[]>([])
const roleList = ref<any[]>([])

const getInfo = () => {
    getDepartList().then(res => {
        departList.value = res.items
    })

    getRoleList().then(res => {
        roleList.value = res.items
    })
}

const dict = computed<any>(() => {
    return $systemStore.dict
})

onMounted(() => {
    getInfo()
    // getRoleData()
    // getDepartData()
})
</script>